package com.lykj.llw.box.ui.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.dinuscxj.itemdecoration.LinearDividerItemDecoration
import com.lykj.lib_base.base.BaseFragment
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.MyCouponAdapter
import com.lykj.llw.box.data.bean.response.MyCouponResponse
import com.lykj.llw.box.databinding.FrgReuseCouponBinding
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody

/**
 * ================================================
 * frag-复用优惠券
 * ================================================
 *
 * @author gosha
 * @date 2023/10/17-11:33
 */
class ReUseCouponFragment : BaseFragment() {
    lateinit var binding: FrgReuseCouponBinding

    private val mAdapter = MyCouponAdapter()
    private val mData = ArrayList<MyCouponResponse.DataDTO.RowsDTO>()
    private var mType: Int? = 0
    private var pageSize = 10
    private var totalPage = 1
    private var pageNo = 1

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {

        binding = FrgReuseCouponBinding.inflate(layoutInflater)
        initUI()
        initData()
        setListener()
        return binding.root
    }

    override fun initUI() {
        initRecyclerView()
    }

    /**
     * 获取我的优惠券(0:未使用  1:已使用)
     */
    private fun obtainMyCoupon(status: String) {
        clearBodyParam()
        initBodyParam()
        bodyParams["status"] = status
        bodyParams["pageNo"] = pageNo
        bodyParams["pageSize"] = pageSize
        RetrofitManager.instance.obtainMyCoupon(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@ReUseCouponFragment, d)
            }

            override fun specificHandle(responseBody: String) {
                val bean = GsonUtils.fromJson(responseBody, MyCouponResponse::class.java)

                totalPage = bean.data.totalPage

                if (bean.data.rows.size > 0) {
                    mData.addAll(bean.data.rows)
                }

                mAdapter.notifyDataSetChanged()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(requireContext(), it)
                }
            }
        }, bodyParams)
    }

    override fun initData() {
        //type 0:未使用 1:已使用 2:已过期
        mType = arguments?.getInt("type", 0)

        obtainMyCoupon("$mType")
    }

    private fun initRecyclerView() {
        val linearLayoutManager = LinearLayoutManager(requireContext())
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.rcvCoupon.layoutManager = linearLayoutManager
        binding.rcvCoupon.setHasFixedSize(true)
        val dividerItemDecoration = LinearDividerItemDecoration(
            requireContext(), LinearDividerItemDecoration.LINEAR_DIVIDER_VERTICAL
        )
        dividerItemDecoration.setDivider(
            resources.getDrawable(
                R.drawable.divider_0dp, resources.newTheme()
            )
        )
        binding.rcvCoupon.addItemDecoration(dividerItemDecoration)
        val emptyView = View.inflate(requireContext(), R.layout.empty_playing, null)
        emptyView.findViewById<TextView>(R.id.tv_desc).text = "暂无优惠券"
        mAdapter.setEmptyView(emptyView)
        mAdapter.data = mData
        binding.rcvCoupon.adapter = mAdapter
    }

    override fun setListener() {
        binding.srfRefresh.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                mData.clear()
                mAdapter.notifyDataSetChanged()
                pageNo = 1
                obtainMyCoupon("$mType")
                refreshLayout.finishRefresh(350, true, false)
                refreshLayout.resetNoMoreData()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageNo == totalPage) {
                    refreshLayout.finishLoadMoreWithNoMoreData()
                    ToastUtils.showShort(requireContext(), "没有更多优惠券数据了")
                    return
                }
                pageNo++
                obtainMyCoupon("$mType")
                refreshLayout.finishLoadMore(350)
            }
        })
    }

    override fun onDestroy() {
        removeDisposables(this)
        super.onDestroy()
    }
}